package smcms.service.cloudstore.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import smcms.service.cloudstore.entity.Permission;
import smcms.service.cloudstore.service.PermissionService;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    WebApplicationContext applicationContext;
    @Value("${spring.application.name}")
    private String serverName;
    @Override
    public List<Permission> getPermissions() throws ClassNotFoundException {
        String[] controllerList = applicationContext.getBeanNamesForAnnotation(RestController.class);
        List<Permission> permissionList = new ArrayList<>();
        for (String s : controllerList) {
            String firstCase = s.substring(0, 1).toUpperCase();
            String secCase = s.substring(1);
            String ClassName = firstCase + secCase;
            Class<?> aClass = Class.forName(serverName.replace("-",".") + ".controller." + ClassName);
            Method[] methods = aClass.getDeclaredMethods();
            List<Permission> methodName = Arrays.stream(methods).map(method -> {
                Permission permission = new Permission();
                permission.setPermission(method.getName());
                return permission;
            }).collect(Collectors.toList());
            permissionList.addAll(methodName);
        }
        return permissionList;
    }
}
